package com.zx.security.block.uitls;

import com.zx.security.common.model.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;

/**
 * <p>
 * description: 安全服务工具类 <br>
 * create: 2024-10-03 23:25
 * </p>
 *
 * @author zhou  xun
 */
public class SecurityUtils {

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户名
     **/
    public static String getUserName() {
        return getAuthentication().getName();
    }

    /**
     * 从认证信息中获取用户ID
     **/
    public static String getUserId() {
        Authentication authentication = getAuthentication();
        if (authentication != null) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof Jwt jwt) {
                return jwt.getClaimAsString("userId");
            }
            if (principal instanceof LoginUser) {
                return ((LoginUser) principal).getId();
            }
        }
        return null;
    }
}